package misc

import (
	"dhfshop/models"
	"errors"
	"strings"
	"time"
    "dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)

//公共通知管理
type Notify struct {
	NotifyId     int64     `orm:"column(notify_id);pk;auto" json:"notify_id" form:"notify_id"`       //自增主键
	TypeId       int       `orm:"column(type_id);default(0);index" json:"type_id" form:"type_id"`    //类型:1=所有店铺显示，2=指定store_ie的店铺显示
	Jump         int       `orm:"column(jump);default(0);index" json:"jump" form:"jump"`             //类型:1=跳转
	StoreId      int64       `orm:"column(store_id);default(0);index" json:"store_id" form:"store_id"` //门店id
	Content      string    `orm:"column(Content)" json:"content" form:"content"`                     //公告内容
	StartAt      time.Time `orm:"column(start_at);type(datetime);index" json:"-" form:"-"`           //生效时间
	EndAt        time.Time `orm:"column(end_at);type(datetime);index" json:"-" form:"-"`             //过期时间
	CreatedAt    time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`  //创建时间
	StartAtStr   string    `orm:"-" json:"start_at,omitempty" form:"start_at"`                       //
	EndAtStr     string    `orm:"-" json:"end_at,omitempty" form:"end_at"`                           //
	CreatedAtStr string    `orm:"-" json:"created_at" form:"-"`                                      //
}

func init() {
	orm.RegisterModel(new(Notify))
}

// 查询
func GetNotify(id int64) (v *Notify, err error) {
	o := models.GetDefaultDB()
	v = &Notify{NotifyId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// 添加
func AddNotify(v *Notify) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

// 更新
func UpdateNotify(m *Notify, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Notify{NotifyId: m.NotifyId}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, k...)
		return
	}
	return
}

// 删除
func DeleteNotify(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Notify{NotifyId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

// 批量查询
func GetAllNotifys(storeIds []int64,query map[string]string, fields []string, order_by map[string]string, offset, limit int) ([]*Notify, int64, error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Notify))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, ","); ok {
			valueArr := strings.Split(v, ",")
			qs = qs.Filter(k, valueArr)
		} else {
			qs = qs.Filter(k, v)
		}
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Notify
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, temp := range lists {
			temp.StartAtStr = temp.StartAt.Format(consts.DATETIME_FORMAT)
			temp.EndAtStr = temp.EndAt.Format(consts.DATETIME_FORMAT)
			temp.CreatedAtStr = temp.CreatedAt.Format(consts.DATETIME_FORMAT)
		}
		return lists, cnt, nil
	}
	return nil, 0, err
}
